package cn.edu.gznu.wecampus.yqfkmj.framework.service;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import cn.edu.gznu.wecampus.core.BusinessException;
import cn.edu.gznu.wecampus.yqfkmj.framework.entity.Domitory;
import cn.edu.gznu.wecampus.yqfkmj.framework.entity.ValidateLog;
import cn.edu.gznu.wecampus.yqfkmj.framework.repository.DomitoryRepository;
import cn.edu.gznu.wecampus.yqfkmj.framework.repository.ValidateLogRepository;

@Service
public class ValidatorService {
	
	@Autowired
	private DomitoryRepository domitoryRepository;
	
	@Autowired
	private List<IMemberDomitoryValidator> memberDomitoryValidators;
	
	@Autowired
	private ValidateLogRepository validateLogRepository;

	public void check(String xgh, String domitoryId) {
		try {
			Domitory domitory = domitoryRepository.findOne(domitoryId);
			if(domitory == null) {
				throw new BusinessException("楼栋不存在");
			}
			memberDomitoryValidators.forEach(memberDomitoryValidator -> {
				if(memberDomitoryValidator.isSuitable(xgh, domitory)) {
					memberDomitoryValidator.validate(xgh, domitory);
				}
			});
			ValidateLog log = new ValidateLog();
			log.setXgh(xgh);
			log.setDomitoryId(domitoryId);
			log.setSuccess(true);
			validateLogRepository.saveAndFlush(log);
		} catch(Exception e) {
			ValidateLog log = new ValidateLog();
			log.setXgh(xgh);
			log.setDomitoryId(domitoryId);
			log.setSuccess(false);
			log.setMsg(e.getMessage());
			validateLogRepository.saveAndFlush(log);
			throw e;
		}
	}
}
